import {PlotTypes} from '../../enum/PlotTypes';
import {Point} from '../../type';

// @ts-ignore
export default class TriangleFlag extends ol.geom.Polygon {
    public params: any;
    public isPlot: boolean = true;
    public fixPointCount: number = 2;

    private readonly _type: PlotTypes;
    private points: Array<Point>;

    constructor(coordinates: any, points: Array<Point>, params: any) {
        super([]);
        this._type = PlotTypes.TRIANGLE_FLAG;
        this.points = [];
        this.params = params;
        if (points && points.length > 0) {
            this.setPoints(points);
        } else if (coordinates && coordinates.length > 0) {
            // @ts-ignore
            this.setCoordinates(coordinates);
        }
    }

    /**
     * 获取标绘类型
     * @return {PlotTypes}
     */
    public getPlotType(): PlotTypes {
        return this._type;
    }

    /**
     * 获取坐标点
     * @return {Array<Point>}
     */
    public getPoints(): Array<Point> {
        return this.points.slice(0);
    }

    /**
     * 获取点数理
     * @return {number}
     */
    public getPointCount(): number {
        return this.points.length;
    }

    /**
     * 更新当前坐标
     * @param point
     * @param index
     */
    public updatePoint(point: Point, index: number): void {
        if (index >= 0 && index < this.points.length) {
            this.points[index] = point;
            this.generate();
        }
    }

    private updateLastPoint(point: Point): void {
        this.updatePoint(point, this.points.length - 1);
    }

    /**
     * 完成绘制
     */
    public finishDrawing(): void {

    }

    private setPoints(value: Array<Point>): void {
        this.points = !value ? [] : value;
        if (this.points.length >= 1) {
            this.generate();
        }
    }

    private generate(): void {
        const count: number = this.getPointCount();
        if (count < 2) {
            return;
        } else {
            // @ts-ignore
            this.setCoordinates([this.calculatePoints(this.points)]);
        }
    }

    /**
     * 插值点数据
     * @param points
     * @private
     */
    private calculatePoints(points: Array<Point>): Array<Point> {
        let components: Array<Point> = [];
        // 至少需要两个控制点
        if (points.length > 1) {
            // 取第一个点和最后一个点
            const startPoint: Point = points[0];
            const endPoint: Point = points[points.length - 1];
            const p1: Point = [endPoint[0], (startPoint[1] + endPoint[1]) / 2];
            const p2: Point = [startPoint[0], (startPoint[1] + endPoint[1]) / 2];
            const p3: Point = [startPoint[0], endPoint[1]];
            components = [startPoint, p1, p2, p3];
        }
        return components;
    }
}